/*
 * Copyright 2009 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


package bw.note;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import bw.util.*;

public class NotebookServlet extends HttpServlet
{
    public static final String ACTION = "action";
    public static final String LIST_INDEX = "list";
    public static final String PAGE_NAME = "name";
    public static final String ADD_PAGE = "addPage";
    public static final String DELETE_PAGE = "deletePage";
    public static final String SET_DEFAULT_PAGE = "setDefaultPage";

    public void doGet ( HttpServletRequest req, HttpServletResponse res ) 
        throws ServletException, IOException
    {
        String action = req.getParameter( ACTION );
        String name = req.getParameter( PAGE_NAME );

        NotebookManager manager = new NotebookManager();

        res.setContentType( "text/xml" );

        PrintWriter out = res.getWriter();

        if ( ADD_PAGE.equals( action ) )
        {
            if ( Util.isNonEmpty( name ) )
            {
                manager.addPage( name );
            }

            printIndex( manager.getPages(), out );
        }
        else if ( DELETE_PAGE.equals( action ) )
        {
            if ( Util.isNonEmpty( name ) )
            {
                manager.deletePage( name );
            }

            printIndex( manager.getPages(), out );
        }
        else if ( SET_DEFAULT_PAGE.equals( action ) )
        {
            manager.setDefaultPage( name );

            out.println( "<notebook />" );
        }
        else if ( LIST_INDEX.equals( action ) )
        {
            printIndex( manager.getPages(), out );
        }

        out.close();
    }

    private void printIndex ( Vector pages, PrintWriter out ) throws IOException
    {
        out.println( "<notebook>" );
        
        for ( Enumeration e = pages.elements(); e.hasMoreElements(); )
        {
            NotebookPage page = (NotebookPage) e.nextElement();
            out.println( page.toXML() );
        }
        
        out.println( "</notebook>" );
    }

}